<script setup lang="ts">
import { Toast } from 'vant'
import { ref } from 'vue'
import { getConsultOrderPayUrl } from '@/api/consult'

const { orderId, show, payCallback } = defineProps<{
  orderId: string
  actualPayment?: number
  onClose?: () => void
  show: boolean
  payCallback?: string
}>()
const emit = defineEmits<{
  (e: 'update:show', val: boolean): void
}>()

const paymentMethod = ref<0 | 1>()

// 跳转支付
const loading = ref(false)
const pay = async () => {
  // 注意支付方式0微信，不能做!判断
  if (paymentMethod.value === undefined) return Toast.fail('请选择支付方式')
  if (paymentMethod.value === 0) return Toast.fail('暂不支持微信支付')
  loading.value = true
  Toast.loading({
    message: '跳转支付',
    duration: 0,
  })
  try {
    // 调用接口获取支付地址
    const res = await getConsultOrderPayUrl({
      orderId, // 订单id
      paymentMethod: paymentMethod.value, // 支付方式 0：微信支付 1：支付宝支付
      payCallback:
        payCallback || import.meta.env.DEV
          ? 'http://localhost:5173/#/room'
          : 'https://ljh-online-consult.netlify.app/#/room', // 回跳地址
    })
    window.location.href = res.payUrl // 跳转支付宝支付地址，不是路由地址
  } catch (error) {
    console.log(error)
  } finally {
    // loading.value = false
  }
}
</script>

<template>
  <!-- 支付方式弹窗 -->
  <van-action-sheet
    :show="show"
    @update:show="emit('update:show', $event)"
    title="选择支付方式"
    :close-on-popstate="false"
    :before-close="onClose"
    :closeable="false"
  >
    <div class="pay-type">
      <p class="amount">￥{{ actualPayment?.toFixed(2) }}</p>
      <van-cell-group>
        <van-cell title="微信支付" @click="paymentMethod = 0">
          <template #icon><cp-icon name="consult-wechat" /></template>
          <template #extra><van-checkbox :checked="paymentMethod === 0" /></template>
        </van-cell>
        <van-cell title="支付宝支付" @click="paymentMethod = 1">
          <template #icon><cp-icon name="consult-alipay" /></template>
          <template #extra><van-checkbox :checked="paymentMethod === 1" /></template>
        </van-cell>
      </van-cell-group>
      <div class="btn">
        <van-button :loading="loading" @click="pay" type="primary" round block>立即支付</van-button>
      </div>
    </div>
  </van-action-sheet>
</template>

<style lang="scss" scoped>
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
